/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');


/*
 *@todo  API20 回帖列表
 * */
exports.getPost = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  var tid = fields.tid;
  var uid = fields.uid;
  var act=fields.act;
  var page = fields.page || 1;
  var pageSize = fields.pagesize || C.post.pageSize;
  var beginIndex = (page - 1) * pageSize;
  // 判断帖子是否存在
  var isThreadExist = yield MPosts.isThreadExist(tid);
  if (!isThreadExist) {
    return F.returnMsg(400, '帖子不存在', 1);
  }
  var manager = fields.manager;
  var statusWhere = 'AND p.status=1';
  var whereArray = [tid];
  var isManager=false;

  if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {
    isManager=true;
  }

  //如果已经登录，则可以查看状态为1，2并且是自己发的回帖
  if (loginStatus.status && loginStatus.uid >0&&!isManager) {
    statusWhere =  ' AND (p.status=1 or (p.status=2 and pc.uid=?)) ';
    whereArray.push(loginStatus.uid);
  }
  if (isManager) {
    statusWhere = '';
  }

  if (uid) {
    statusWhere = statusWhere + ' AND pc.uid=?';
    whereArray.push(uid);
  }
    whereArray.push(tid);
  whereArray.push(parseInt(beginIndex));
  whereArray.push(parseInt(pageSize));
  var posts = yield mysql.query(
    'SELECT p.tid,p.pid,p.uid,p.imgext,p.timeline,p.status,p.users,u.nickname,u.face,u.vip,mui.integral,mui.talentid,IFNULL(pc.post,"") post,p.vest as isVest,p.liketimes  ' +
    'FROM mh_post p ' +
    'LEFT JOIN mh_user u ON p.uid = u.uid ' +
    'LEFT JOIN mh_user_info mui ON mui.uid = u.uid ' +
    'LEFT JOIN mh_post_content pc ON p.pid = pc.pid ' +
    'WHERE p.tid=? ' + statusWhere + ' AND p.pid<>(select pid from mh_thread where tid=?) ' +
    'ORDER BY p.pid DESC ' +
    'LIMIT ?,? ', whereArray);
    let myLikedPost;
    let myLikedReply;
    if (loginStatus.status) {
      //    点赞帖
      myLikedPost = yield F.userList(parseInt(loginStatus.uid), 4);
      //点赞回帖
      myLikedReply=yield F.userList(parseInt(loginStatus.uid),5);
    }

  if (posts.length > 0) {
    for (var i = 0; i < posts.length; i++) {
      var post = posts[i];
      delete post.imgext;
      post.type = 18;
      post.faceUrl = F.generateFaceUrl(post.face, post.uid);
      delete post.face;

      post.like = false;
      // 回帖是否点赞
      if (myLikedReply && post.pid) {
        if (_.contains(myLikedReply, post.pid.toString())) {
          post.like = true;
        }
      }

      var level = F.getLevelfromIntegral(post.integral);
      post.level = level.lid;
      delete post.integral;
      //显示达人称号
      //显示达人等级
      if (post.talentid > 0 && post.vip == 0) {// 是否达人  (VIP 无达人属性)
        post.talent = F.getTalentInfo(post.talentid).name;
        post.talent_level = level.talent_level; //  this.getTalentInfo(threads[i].talentid).talent_level;
      }
      else {
        post.talent = '';
        post.talentid = 0
      }

      var users = post.users;
      post.users = [];
      if (users.length > 0) {
        var userIdArr = users.split(',');
        for (var j in userIdArr) {
          var userData = yield mysql.queryOne('SELECT uid,nickname FROM mh_user WHERE uid=?', [userIdArr[j]]);
          if (userData) {
            post.users.push({uid: userData['uid'], nickname: userData['nickname']});
          }
        }
      }
    }
  }else if(act==1){
    return F.returnMsg(300, '已没有数据了', 3);
  }

  if(act==2){//获取推荐阅读，热门评论列表
     let others_arr=[];
     //取推荐阅读开始
     let tidArr=[];
     let params={act:1,tid:tid};
     let reccomnd_thread=[];
     if (page ==1)
       reccomnd_thread = yield F.recommendThread(params);
     if (reccomnd_thread && reccomnd_thread.length>0 && page == 1) {
       if (reccomnd_thread.length > 4) {
         reccomnd_thread.splice(4, reccomnd_thread.length - 4);
       }
       others_arr.push({type: 16, title: "你可能感兴趣", style: 1});

       for (let thread of reccomnd_thread) {
         tidArr.push(thread.tid);
       }
       let threads = yield F.returnThreadInfo(tidArr);
       for (let thread of threads) {
         let firstValidImageText = '';
         //find the 1st valid in the thread begin
         let imgIdArr = [];
         if (!_.isEmpty(thread.validimg)) {
           imgIdArr = thread.validimg.split(',');
           for (let img_pair of imgIdArr) {
             let tempData = img_pair.split('-');
             if (tempData[1] == 1) {//the 1st valid image
               firstValidImageText = thread.imagestring.split(',')[tempData[0]];
               break;
             }
           }
         }
         //find the 1st valid in the thread end

         //get the field whether login user parise the thread or not
         // 主题帖是否点赞
         thread.like = false;
         if (myLikedPost && thread.pid) {
           if (_.contains(myLikedPost, thread.pid.toString())) {
             thread.like = true;
           }
         }
         thread.post = _s.truncate(thread.post, 25, '...');
         thread.type = 17;//推荐帖子type=17
         thread.style = 0;
         if (fields.app_ver_arr.code > 45) {
           thread.style = 1;//code45以后，使用新的展示样式
         }
         thread.ttype = 0;//0为普通帖，1 2为美容贴
         thread.imgUrl = imgRule.str2imgURI(firstValidImageText)[0].imgURI + C.upyun.suffix;
         others_arr.push(_.pick(thread, 'post', 'replies', 'liketimes', 'type', 'imgUrl', 'ttype', 'tid', 'like','style'));
       }
     }
     //取推荐阅读结束

     //获取热门评论列表开始
     if(page==1){//如果是第一页时，插入热门评论
       let hot_record = _.filter(posts, function (record) {
         return record.liketimes >= C.post.hotPost;
       });
       if(hot_record&&hot_record.length>0){
         //插入评论栏目开始
         others_arr.push({type:16,title:'评论',style:1});
         //插入评论栏目结束
         _.sortBy(hot_record,'liketimes');
         for (let i = hot_record.length - 1; i >= hot_record.length-3 && i>=0; i--) {
           let record=_.clone(hot_record[i]);
           record.hot=1;
           others_arr.push(record);
         }
         others_arr.push({type:16,title:'以上为热门评论',style:2,latestReply:1});
       }else{
         //插入评论栏目开始
         others_arr.push({type:16,title:'评论',style:1,latestReply:1});
         //插入评论栏目结束
       }
     }
     //获取热门评论列表结束
     for(let i=others_arr.length-1;i>=0;i--){
       posts.unshift(others_arr[i]);
     }
   }
    return F.returnMsg(200, '回帖列表返回成功', 3, {pageIndex: page, items: posts});
};
